13. Exercise: Refresh Data with DiffUtil

L7 21 DiffUtil SC

Now it’s your turn to complete this exercise yourself.

In this step you'll take the Adapter you finished in the last section and add DiffUtils to calculate changes when the list changes.

When you've completed this exercise you will have refactored the SleepNightAdapter to use ListAdapter, and replaced notifyDataSetChanced with the more optimized DiffUtil.

  1. At the bottom of SleepNightAdapter.kt, create a new class SleepNightDiffCallback that extends DiffUtil.ItemCallback<SleepNight>.

    class SleepNightDiffCallback : 
           DiffUtil.ItemCallback<SleepNight>() {
    }


  2. In SleepNightDiffCallback override areItemsTheSame.

    Two items are the same if their nightId values are equal.


  3. Override areContentsTheSame in SleepNightDiffCallback.

    Two items are the same if they have the same value, oldItem == newItem.


  4. Update SleepNightAdapter to extend ListAdapter with a SleepNightDiffCallback() parameter:

    class SleepNightAdapter : ListAdapter<SleepNight, SleepNightAdapter.ViewHolder>(SleepNightDiffCallback())

    Make sure to import ListAdapter from androidx.recyclerview.widget.ListAdapter.

  5. Delete the data field and getItemCount().

    Remove the code for val data and getItemCount.

    NOTE: Your code will not compile after this step. We'll fix that in the next few steps.


  6. In onBindViewHolder() replace data[position] with a call to getItem().


  7. In SleepTrackerFragment nights observer, replace adapter.data assignment with a call to adapter.submitList().

  8. Run the app again! You should see the items animate when you start a sleep night.

If you want to start at this step, you can download this exercise from: Step.07-Exercise-Add-DiffUtil-to-Adaptera.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here: Step.07-Solution-Add-DiffUtil-to-Adapter, or using this git diff.

Task Description:

Complete these tasks to implement DiffUtil to calculate changes when the list changes.

Task List:

Task Feedback:

Great job! Add a few items to see RecyclerView animate the changes!

Reference Documentation